package com.yz.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.fluent.Request;
import org.springframework.util.Assert;

import com.yz.crm.company.model.Company;
import com.yz.crm.db.model.BaseCompany;
import com.yz.crm.passport.constant.PassportConst;
import com.yz.crm.passport.model.SessionUser;

public final class WebUtils {
    private static final   Log log = LogFactory.getLog(WebUtils.class);
    private WebUtils() {
    }

    public static String getContentPath(HttpServletRequest request) {
        String path = request.getContextPath();
        return path;
    }

    public static String getWebPath(HttpServletRequest request) {
        String strDirPath = request.getSession().getServletContext().getRealPath("/");
        return strDirPath;
    }
    
    public static SessionUser getLoginUser(HttpServletRequest request) {
    	HttpSession session=request.getSession();
    	if(session!=null){
    		SessionUser user = (SessionUser)session.getAttribute(PassportConst.SESSION_KEY_USER);
        	return user;
    	}
    	return null;
    }

    public static String calRefererUrlToRedirect(HttpServletRequest request) {
        String referer = request.getHeader("Referer");
        String ip = WebUtils.getIp(request);
        String serverUrl = getRequestContentUrl(request);
        String memberUrl = null;
        if (org.apache.commons.lang3.StringUtils.endsWith(serverUrl, "/")) {
            memberUrl = serverUrl + "index";
        } else {
            memberUrl = serverUrl + "/index";
        }
        return "redirect:" + memberUrl;
    }

    public static String getRequestContentUrl(HttpServletRequest request) {
        String requestURL = request.getRequestURL().toString();
        String requestURI = request.getRequestURI();
        String contextPath = request.getContextPath();
        String result = org.apache.commons.lang3.StringUtils.removeEnd(requestURL, requestURI) + contextPath;

        log.debug("----->>>requestURL=" + requestURL + ",requestURI=" + requestURI
                + ",contextPath=" + contextPath + ",url=" + result);
        return result;
    }
    public static String getIp(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        String ip = getIp(request.getHeader("X-Real-IP"));
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = getIp(request.getHeader("X-Forwarded-For"));
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = getIp(request.getHeader("Proxy-Client-IP"));
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = getIp(request.getHeader("WL-Proxy-Client-IP"));
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = getIp(request.getRemoteAddr());
        }
        return ip;
    }

    private static String getIp(String ip) {
        if (ip == null || ip.length() == 0) {
            return null;
        }
        String ipFilterList ="";// Propertyutils.getValue("ip.filter.list");
        String[] ipStrArray = StringUtils.split(ipFilterList, ",");
        if (ipStrArray == null || ipStrArray.length == 0) {
            return ip;
        }
        String[] strArray = StringUtils.split(ip, ",");
        if (strArray == null || strArray.length == 0) {
            return ip;
        }
        for (String str : strArray) {
            str = StringUtils.trim(str);
            if (str == null || str.length() == 0) {
                continue;
            }
            if (!ArrayUtils.contains(ipStrArray, str)) {
                return str;
            }
        }
        return null;
    }

    /**
     * 检测是否是微信请求过来的
     *
     * @param request
     * @return
     */
    public static boolean isWeChatRequest(HttpServletRequest request) {
        String ua = org.apache.commons.lang3.StringUtils.lowerCase(request.getHeader("user-agent"));
        if (ua != null && ua.indexOf("micromessenger") > 0) {// 是微信浏览器
            return true;
        }
        return false;
    }
    public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, Integer maxAge, String path, String domain, Boolean secure) {
        Assert.notNull(request);
        Assert.notNull(response);
        Assert.hasText(name);
        try {
            name = URLEncoder.encode(name, "UTF-8");
            value = URLEncoder.encode(value, "UTF-8");
            Cookie cookie = new Cookie(name, value);
            if (maxAge != null) {
                cookie.setMaxAge(maxAge);
            }
            if (StringUtils.isNotEmpty(path)) {
                cookie.setPath(path);
            }
            if (StringUtils.isNotEmpty(domain)) {
                cookie.setDomain(domain);
            }
            if (secure != null) {
                cookie.setSecure(secure);
            }
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, Integer maxAge) {

        addCookie(request, response, name, value, maxAge, null, null, null);
    }

    //
    public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value) {

        addCookie(request, response, name, value, null, null, null, null);
    }

    public static String getCookie(HttpServletRequest request, String name) {
        Assert.notNull(request);
        Assert.hasText(name);
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            try {
                name = URLEncoder.encode(name, "UTF-8");
                for (Cookie cookie : cookies) {
                    if (name.equals(cookie.getName())) {
                        return URLDecoder.decode(cookie.getValue(), "UTF-8");
                    }
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String name, String path, String domain) {
        Assert.notNull(request);
        Assert.notNull(response);
        Assert.hasText(name);
        try {
            name = URLEncoder.encode(name, "UTF-8");
            Cookie cookie = new Cookie(name, null);
            cookie.setMaxAge(0);
            if (StringUtils.isNotEmpty(path)) {
                cookie.setPath(path);
            }
            if (StringUtils.isNotEmpty(domain)) {
                cookie.setDomain(domain);
            }
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

	public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String name) {

		removeCookie(request, response, name, null, null);
	}

    public static String getParameter(String queryString, String encoding, String name) {
        String[] parameterValues = getParameterMap(queryString, encoding).get(name);
        return parameterValues != null && parameterValues.length > 0 ? parameterValues[0] : null;
    }

    public static String[] getParameterValues(String queryString, String encoding, String name) {
        return getParameterMap(queryString, encoding).get(name);
    }

    public static Map<String, String[]> getParameterMap(String queryString, String encoding) {
        Map<String, String[]> parameterMap = new HashMap<String, String[]>();
        Charset charset = Charset.forName(encoding);
        if (StringUtils.isNotEmpty(queryString)) {
            byte[] bytes = queryString.getBytes(charset);
            if (bytes != null && bytes.length > 0) {
                int ix = 0;
                int ox = 0;
                String key = null;
                String value = null;
                while (ix < bytes.length) {
                    byte c = bytes[ix++];
                    switch ((char) c) {
                        case '&':
                            value = new String(bytes, 0, ox, charset);
                            if (key != null) {
                                putMapEntry(parameterMap, key, value);
                                key = null;
                            }
                            ox = 0;
                            break;
                        case '=':
                            if (key == null) {
                                key = new String(bytes, 0, ox, charset);
                                ox = 0;
                            } else {
                                bytes[ox++] = c;
                            }
                            break;
                        case '+':
                            bytes[ox++] = (byte) ' ';
                            break;
                        case '%':
                            bytes[ox++] = (byte) ((convertHexDigit(bytes[ix++]) << 4) + convertHexDigit(bytes[ix++]));
                            break;
                        default:
                            bytes[ox++] = c;
                    }
                }
                if (key != null) {
                    value = new String(bytes, 0, ox, charset);
                    putMapEntry(parameterMap, key, value);
                }
            }
        }
        return parameterMap;
    }

    private static void putMapEntry(Map<String, String[]> map, String name, String value) {
        String[] newValues = null;
        String[] oldValues = map.get(name);
        if (oldValues == null) {
            newValues = new String[]{value};
        } else {
            newValues = new String[oldValues.length + 1];
            System.arraycopy(oldValues, 0, newValues, 0, oldValues.length);
            newValues[oldValues.length] = value;
        }
        map.put(name, newValues);
    }

    private static byte convertHexDigit(byte b) {
        if ((b >= '0') && (b <= '9')) {
            return (byte) (b - '0');
        }
        if ((b >= 'a') && (b <= 'f')) {
            return (byte) (b - 'a' + 10);
        }
        if ((b >= 'A') && (b <= 'F')) {
            return (byte) (b - 'A' + 10);
        }
        throw new IllegalArgumentException();
    }

}